package za.co.dylanjaneke.airdownloader.command
{
	import flash.data.SQLStatement;
	import flash.events.SQLEvent;
	
	import mx.controls.Alert;
	
	import za.co.dylanjaneke.airdownloader.controller.data.ConnectionManager;
	import za.co.dylanjaneke.airdownloader.events.LoadSettingsEvent;
	import za.co.dylanjaneke.airdownloader.events.SaveSettingsEvent;
	import za.co.dylanjaneke.airdownloader.model.SettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.StatusPM;
	import za.co.dylanjaneke.airdownloader.model.TrackerSettingsScreenPM;
	import za.co.dylanjaneke.airdownloader.model.vo.SettingsVO;
	import za.co.dylanjaneke.airdownloader.util.ViLogger;

	/**
	 * Author: Dylan Janeke
	 */
	[Name("saveSettingsCommand")]
	public class SaveSettingsCommand
	{
		private static const log:ViLogger=
			new ViLogger(SaveSettingsCommand);
		
		[Inject]
		public var connectionManager:ConnectionManager;
		
		[Inject]
		public var settingsPM:TrackerSettingsScreenPM;
		
		[Inject]
		public var statusPM:StatusPM;
		
		[Observer]
		public function handleSaveSettings(event:SaveSettingsEvent): void
		{
			statusPM.status= "Saving Settings...";
			log.info("saveSettingsCommand -->" + event);
			if(settingsPM.vo == null)
			{
				connectionManager.executeStatement(SettingsVO.createInsert(event.vo, connectionManager.createStatement()),onSqlComplete);
			}
			else
			{
				connectionManager.executeStatement(SettingsVO.createUpdate(event.vo, connectionManager.createStatement()),onSqlComplete);
			}
		}
		
		protected function onSqlComplete(event:SQLEvent): void
		{
			GlobalEventDispatcher.raiseEvent(new LoadSettingsEvent());
		}
	}
}